#pragma once
#include <vector>
#include <iostream>
#include <pthread.h>
#include <functional>
#include <string>
#include <ctime>

//static int thread_num = 1;
//static int thread_count = 0;
static pthread_mutex_t conut_mutex = PTHREAD_MUTEX_INITIALIZER;

class Mythread
{
    static void *Routine(void *Args)
    {
        Mythread *ts = static_cast<Mythread *>(Args);
        return ts->Entery();
        //return nullptr;
    }

public:
    Mythread(std::function<void *()> fc)
        : _fc(fc), _name(""), _isrunning(false)
    {}

    //禁用拷贝和赋值
    Mythread(const Mythread&) = delete;
    Mythread& operator=(const Mythread&) = delete;

    bool Start()
    {
        if(_isrunning) return false;
        // pthread_mutex_lock(&conut_mutex);
        // _name = "Mythread " + std::to_string(thread_num);
        // thread_num++;
        // thread_count++;
        // pthread_mutex_unlock(&conut_mutex);
        // if (thread_count >= 1)
        _start_timestamp=time(0);
        _isrunning = true;
        pthread_create(&_tid, nullptr, Routine, this);
        return true;
    }

    bool Join()
    {
        if(!_isrunning) return false;
        pthread_join(_tid, nullptr);
        // pthread_mutex_lock(&conut_mutex);
        // thread_count--;
        // pthread_mutex_unlock(&conut_mutex);
        // if (thread_count == 0)
        _isrunning = false;
        return true;
    }

    bool Detach()
    {
        if(!_isrunning) return false;
        pthread_detach(_tid);
        _isrunning=false;
        return true;
    }

    // std::string GetName()
    // {
    //     return _name;
    // }

    bool Cancel()
    {
        if(!_isrunning) return false;
        pthread_cancel(_tid);
        _isrunning=false;
        return true;
    }
    bool IsRunning()
    {
        return _isrunning;
    }

    time_t GetStartTime()
    {
        return _start_timestamp;
    }

    time_t GetRunTime()
    {
        return time(nullptr) - _start_timestamp;
    }
    ~Mythread()
    {
        if (IsRunning())
        {
            std::cerr << "Warning: Thread " << _name << " was not properly joined!" << std::endl;
        }
    }
private:
    void* Entery()
    {
        return _fc();
    }

private:
    pthread_t _tid = 0;
    std::string _name;
    std::function<void *()> _fc;
    // uint64_t _start_timestamp;
    time_t _start_timestamp;
    bool _isrunning;
    //bool _isJoin;
    //bool _isdetached;
};